package com.zx.sa.controller;

import com.zx.sa.common.ModelType;
import com.zx.sa.controller.valid.ValidMessage;
import com.zx.sa.service.ChatService;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import reactor.core.publisher.Flux;

@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/stream")
public class ChatStreamController {

    private final ChatService chatService;

    public ChatStreamController(ChatService chatService) {
        this.chatService = chatService;
    }

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("models", ModelType.getModels());
        return "stream";
    }

    /**
     * 文本流
     */
    @ValidMessage
    @GetMapping(value = "/chatStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Map<String, Object>> chatStream(
            @RequestParam(value = "msg", defaultValue = "") String msg,
            @RequestParam(value = "modelType", defaultValue = ModelType.DEFAULT) String modelType
    ) {
        return chatService.chatStream(msg, modelType)
                .map(this::createResponse);
    }

    /**
     * 辅助方法用于构建 JSON 响应
     */
    private Map<String, Object> createResponse(String content) {
        Map<String, Object> response = new HashMap<>();
        response.put("content", content);
        return response;
    }

} 